<?php

namespace App\Models\Traits;

use App\Util\ChatUtil;
use Illuminate\Database\Eloquent\Model;

trait SetFirstCharAttribute
{
    protected static function bootSetFirstCharAttribute()
    {
        static::creating(function (Model $model) {
            self::getPinyinAttribute($model);
        });

        static::created(function (Model $model) {
            self::getPinyinAttribute($model);
        });
    }

    protected static function getPinyinAttribute(Model $model)
    {
        if (\Schema::hasColumn($model->getTable(), 'pinyin')) {
            $field = $model->getAttribute('nickname');
            if ($field) {
                $pinyinValue = ChatUtil::getFirstChar($field);
                $model->setAttribute('pinyin', $pinyinValue);
            }
        }
    }

}
